package com.sun.myproject.bookservlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.sun.myproject.bean.Book;
import com.sun.myproject.dao.BookDao;
import com.sun.myproject.daoimpl.BookDaoImpl;

@WebServlet("/AddBookServlet")
@MultipartConfig
public class AddBookServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public AddBookServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
			System.out.println("----===-==-=-=来了");

			// 1. 获取客户端提交上来的数据
			String bookname = request.getParameter("bookname");
			System.out.println(bookname);
			String author = request.getParameter("author");
			System.out.println(author);
			String publish = request.getParameter("publish");
			System.out.println(publish);
			System.out.println(request.getParameter("bookcount"));
			int bookcount = Integer.parseInt(request.getParameter("bookcount"));
			System.out.println(bookcount);
			String booktype = request.getParameter("booktype");

			System.out.println(bookname);

			PrintWriter out = response.getWriter();
			// 创建目录
			File path = new File(request.getServletContext().getRealPath("\\BookImg"));
			
			// 获取文件
			Part img = request.getPart("pic");
			// 文件名
			

			String header = img.getHeader("content-disposition");
			System.out.println(header);
			// 获取文件名
			String fileName = getFileName(header);
			System.out.println("-------" + fileName);
			// 文件全路径
			String filePath = path.getPath() + File.separator + fileName;
			// 写入文件
			img.write(filePath);
			
			
			// 2. 添加到数据库

			Book Book = new Book(0, bookname, publish, bookcount, booktype, author, fileName);
			BookDao service = new BookDaoImpl();
			service.insert(Book);

			request.getRequestDispatcher("BookListServlet").forward(request, response);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String getFileName(String header) {

		String[] tempArr1 = header.split(";");

		String[] tempArr2 = tempArr1[2].split("=");

		String fileName = tempArr2[1].substring(tempArr2[1].lastIndexOf("\\") + 1).replaceAll("\"", "");
		return fileName;
	}

}
